<template>
  <span v-if="loading">加载中...</span>
  <span v-else>{{ userName }}</span>
</template>

<script setup lang="ts">
import { ref, watch } from 'vue'
import * as UserApi from '@/api/system/user'

const props = defineProps<{
  userId: number | string | null | undefined
}>()

const userName = ref<string>('')
const loading = ref<boolean>(false)

// 缓存已加载的用户
const userCache = new Map<number, string>()

// 获取单个用户信息
const getUserName = async (id: number): Promise<string> => {
  if (userCache.has(id)) {
    return userCache.get(id)!
  }
  try {
    const user = await UserApi.getUser(id)
    const name = user?.nickname || '未知用户'
    userCache.set(id, name)
    return name
  } catch (e) {
    console.error(`获取用户失败（ID: ${id}）`, e)
    return '未知用户'
  }
}

// 主函数：根据传入 userId（单个或多个）设置 userName
const fetchUser = async () => {
  const raw = props.userId
  if (!raw) {
    userName.value = ''
    return
  }

  loading.value = true
  try {
    const ids = String(raw)
      .split(',')
      .map(s => Number(s.trim()))
      .filter(id => !isNaN(id))

    const nameList = await Promise.all(ids.map(id => getUserName(id)))
    userName.value = nameList.join(', ')
  } finally {
    loading.value = false
  }
}

// 监听 userId 变化
watch(
  () => props.userId,
  () => {
    fetchUser()
  },
  { immediate: true }
)
</script>
